<template>
  <div class="icon-picker">
    <el-popover
      v-model:visible="visible"
      placement="bottom"
      :width="380"
      trigger="click"
    >
      <template #reference>
        <div class="icon-selector">
          <div class="icon-content">
            <div class="icon-display">
              <el-icon v-if="selectedIcon" :size="20">
                <component :is="selectedIconComponent" />
              </el-icon>
              <el-icon v-else :size="20" color="#909399">
                <CircleClose />
              </el-icon>
            </div>
            <div class="selector-arrow">
              <el-icon :size="12">
                <CaretBottom />
              </el-icon>
            </div>
          </div>
          <div class="clear-button" v-if="selectedIcon" @click.stop="clearIcon">
            <el-icon :size="12">
              <CircleClose />
            </el-icon>
          </div>
        </div>
      </template>
      
      <div class="icon-picker-content">
        <div class="icon-picker-header">
          <el-input
            v-model="searchText"
            placeholder="搜索图标..."
            clearable
            size="small"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="icon-categories" v-if="!searchText">
          <el-scrollbar height="40px">
            <div class="category-tabs">
              <div
                v-for="category in categories"
                :key="category"
                class="category-tab"
                :class="{ active: currentCategory === category }"
                @click="currentCategory = category"
              >
                {{ category }}
              </div>
            </div>
          </el-scrollbar>
        </div>
        
        <div class="icon-picker-body">
          <div class="icon-grid">
            <div
              v-for="icon in displayIcons"
              :key="icon.name"
              class="icon-item"
              :class="{ active: modelValue === icon.name }"
              @click="selectIcon(icon)"
            >
              <el-icon :size="18">
                <component :is="icon.component" />
              </el-icon>
            </div>
          </div>
          <div v-if="displayIcons.length === 0" class="no-icons">
            <el-icon :size="48" color="#c0c4cc"><Search /></el-icon>
            <p>没有找到匹配的图标</p>
          </div>
        </div>
        
        <div class="icon-picker-footer">
          <el-button size="small" text @click="clearIcon" style="margin-right: 8px;">清除</el-button>
          <span class="icon-count">{{ displayIcons.length }} 个图标</span>
        </div>
      </div>
    </el-popover>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineAsyncComponent } from 'vue'
import { CircleClose, CaretBottom, Search } from '@element-plus/icons-vue'
import * as lucideIcons from 'lucide-vue-next'

interface IconOption {
  name: string
  component: any
  category: string
}

const props = defineProps<{
  modelValue: string
}>()

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const visible = ref(false)
const searchText = ref('')
const currentCategory = ref('全部')

// 常用图标列表 - 包含Element Plus和Lucide图标
const elementPlusIcons = [
  // 系统管理
  'House', 'User', 'Setting', 'Lock', 'Unlock', 'Key',
  // 活动管理
  'Calendar', 'Star', 'Trophy', 'Medal', 'Flag', 'Location',
  // 评估管理
  'Document', 'Edit', 'Check', 'Close', 'CircleCheck',
  'CircleClose', 'Warning', 'InfoFilled',
  // 指标管理
  'DataAnalysis', 'PieChart', 'Histogram', 'Grid',
  'Operation', 'Monitor', 'Odometer',
  // 通用
  'Menu', 'More', 'MoreFilled', 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown',
  'Upload', 'Download', 'Delete', 'EditPen', 'Search', 'Refresh', 'Plus',
  'Minus', 'Close', 'Check', 'CirclePlus', 'CircleMinus', 'Remove', 'View',
  'Hide', 'Message', 'Bell', 'Phone', 'Link', 'Share', 'UploadFilled',
  'Folder', 'FolderOpened', 'Files', 'Collection', 'CollectionTag'
]

// Lucide图标库 - 更丰富的图标选择
const lucideIconNames = [
  // 系统管理
  'Settings', 'UserCircle', 'Users', 'Shield', 'ShieldCheck', 'KeyRound', 'LockIcon', 'UnlockIcon',
  // 活动管理  
  'CalendarDays', 'CalendarClock', 'StarIcon', 'Award', 'TrophyIcon', 'FlagIcon', 'MapPin', 'MapIcon',
  // 评估管理
  'FileText', 'FileCheck', 'FileX', 'CheckCircle', 'XCircle', 'AlertTriangle', 'InfoIcon', 'ClipboardCheck',
  // 指标管理
  'BarChart3', 'BarChart2', 'BarChartIcon', 'PieChartIcon', 'TrendingUp', 'Activity', 'Gauge', 'LineChart',
  // 通用工具
  'MenuIcon', 'MoreHorizontal', 'MoreVertical', 'ArrowLeftCircle', 'ArrowRightCircle', 'ArrowUpCircle', 'ArrowDownCircle',
  'UploadCloud', 'DownloadCloud', 'Trash2', 'Edit3', 'SearchIcon', 'RotateCcw', 'PlusCircle', 'MinusCircle',
  'Eye', 'EyeOff', 'MessageSquare', 'BellIcon', 'PhoneIcon', 'MailIcon', 'Link2', 'ShareIcon',
  'FolderIcon', 'FolderOpen', 'FileIcon', 'Bookmark', 'BookmarkPlus', 'TagIcon',
  // 新增分类 - 数据分析
  'Database', 'Server', 'Cloud', 'HardDrive', 'CpuIcon', 'MemoryStick',
  // 新增分类 - 用户界面
  'HomeIcon', 'Layout', 'PanelLeft', 'PanelRight', 'Sidebar', 'Columns', 'Layers', 'Palette',
  // 新增分类 - 操作图标
  'Play', 'Pause', 'StopCircle', 'SkipBack', 'SkipForward', 'Rewind', 'FastForward', 'Repeat',
  // 新增分类 - 社交和沟通
  'MessageCircle', 'MessagesSquare', 'Send', 'MailOpen', 'MailPlus', 'MailCheck', 'Inbox', 'PaperclipIcon',
  // 新增分类 - 安全和权限
  'Fingerprint', 'EyeIcon', 'EyeOffIcon', 'ShieldAlert', 'ShieldQuestion', 'ShieldOff', 'KeySquare', 'LockKey',
  // 新增分类 - 文件和文档
  'FilePlus', 'FileMinus', 'FileEdit', 'FileSearch', 'FileLock', 'FileTextIcon', 'FileSpreadsheet', 'FileArchive',
  // 新增分类 - 导航和方向
  'ChevronLeft', 'ChevronRight', 'ChevronUp', 'ChevronDown', 'ChevronsLeft', 'ChevronsRight', 'StepBack', 'StepForward',
  // 新增分类 - 状态和指示
  'CheckSquare', 'Square', 'CircleIcon', 'CircleDot', 'Octagon', 'Hexagon', 'Triangle', 'Diamond'
]

// 合并所有图标
const commonIcons = [...elementPlusIcons, ...lucideIconNames]

// 动态导入图标组件
const iconComponents = commonIcons.reduce((acc, iconName) => {
  // 首先尝试从Element Plus图标库导入
  acc[iconName] = defineAsyncComponent(() => 
    import('@element-plus/icons-vue').then(module => {
      if (module[iconName as keyof typeof module]) {
        return module[iconName as keyof typeof module]
      }
      // 如果Element Plus中没有，尝试从Lucide图标库导入
      return import('lucide-vue-next').then(lucideModule => {
        return lucideModule[iconName as keyof typeof lucideModule] || null
      })
    }).catch(() => {
      // 如果都导入失败，返回null
      return null
    })
  )
  return acc
}, {} as Record<string, any>)

const icons: IconOption[] = commonIcons.map(name => ({
  name,
  component: iconComponents[name],
  category: getIconCategory(name)
}))

function getIconCategory(iconName: string): string {
  // Element Plus 图标分类
  if (['House', 'User', 'Setting', 'Lock', 'Unlock', 'Key'].includes(iconName)) {
    return '系统管理'
  }
  if (['Calendar', 'Star', 'Trophy', 'Medal', 'Flag', 'Location'].includes(iconName)) {
    return '活动管理'
  }
  if (['Document', 'Edit', 'Check', 'Close', 'CircleCheck', 'CircleClose', 'Warning', 'InfoFilled'].includes(iconName)) {
    return '评估管理'
  }
  if (['DataAnalysis', 'PieChart', 'Histogram', 'Grid', 'Operation', 'Monitor', 'Odometer'].includes(iconName)) {
    return '指标管理'
  }
  
  // Lucide 图标分类
  if (['Settings', 'UserCircle', 'Users', 'Shield', 'ShieldCheck', 'KeyRound', 'LockIcon', 'UnlockIcon'].includes(iconName)) {
    return '系统管理'
  }
  if (['CalendarDays', 'CalendarClock', 'StarIcon', 'Award', 'TrophyIcon', 'FlagIcon', 'MapPin', 'MapIcon'].includes(iconName)) {
    return '活动管理'
  }
  if (['FileText', 'FileCheck', 'FileX', 'CheckCircle', 'XCircle', 'AlertTriangle', 'InfoIcon', 'ClipboardCheck'].includes(iconName)) {
    return '评估管理'
  }
  if (['BarChart3', 'BarChart2', 'BarChartIcon', 'PieChartIcon', 'TrendingUp', 'Activity', 'Gauge', 'LineChart', 'Database', 'Server', 'Cloud', 'HardDrive', 'CpuIcon', 'MemoryStick'].includes(iconName)) {
    return '指标管理'
  }
  if (['HomeIcon', 'Layout', 'PanelLeft', 'PanelRight', 'Sidebar', 'Columns', 'Layers', 'Palette'].includes(iconName)) {
    return '界面设计'
  }
  if (['Play', 'Pause', 'StopCircle', 'SkipBack', 'SkipForward', 'Rewind', 'FastForward', 'Repeat'].includes(iconName)) {
    return '媒体控制'
  }
  if (['MessageCircle', 'MessagesSquare', 'Send', 'MailOpen', 'MailPlus', 'MailCheck', 'Inbox', 'PaperclipIcon'].includes(iconName)) {
    return '消息通讯'
  }
  if (['Fingerprint', 'EyeIcon', 'EyeOffIcon', 'ShieldAlert', 'ShieldQuestion', 'ShieldOff', 'KeySquare', 'LockKey'].includes(iconName)) {
    return '安全权限'
  }
  if (['FilePlus', 'FileMinus', 'FileEdit', 'FileSearch', 'FileLock', 'FileTextIcon', 'FileSpreadsheet', 'FileArchive'].includes(iconName)) {
    return '文件管理'
  }
  
  return '通用'
}

const categories = computed(() => {
  const cats = ['全部', ...new Set(icons.map(icon => icon.category))]
  return cats
})

const filteredIcons = computed(() => {
  if (!searchText.value) return icons
  const search = searchText.value.toLowerCase()
  return icons.filter(icon => 
    icon.name.toLowerCase().includes(search) ||
    icon.category.toLowerCase().includes(search)
  )
})

const displayIcons = computed(() => {
  if (searchText.value) {
    return filteredIcons.value
  }
  if (currentCategory.value === '全部') {
    return icons
  }
  return icons.filter(icon => icon.category === currentCategory.value)
})

const selectedIcon = computed(() => {
  return props.modelValue || ''
})

const selectedIconComponent = computed(() => {
  if (!props.modelValue) return null
  return iconComponents[props.modelValue] || null
})

function selectIcon(icon: IconOption) {
  emit('update:modelValue', icon.name)
  visible.value = false
}

function clearIcon() {
  emit('update:modelValue', '')
  visible.value = false
}
</script>

<style scoped>
.icon-picker {
  display: block;
  width: 100%;
}

.icon-selector {
  display: flex;
  width: 100%;
  height: 42px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
  padding: 0;
  position: relative;
  align-items: center;
}

.icon-selector:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.icon-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: 100%;
  padding: 0 28px 0 12px;
}

.icon-display {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  margin-right: 8px;
}

.selector-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  margin-left: 8px;
  position: relative;
  right: 16px;
}

.clear-button {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: rgba(144, 147, 153, 0.1);
  color: #909399;
  cursor: pointer;
  transition: all 0.3s;
  z-index: 10;
}

.clear-button:hover {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.icon-picker-content {
  padding: 12px;
}

.icon-picker-header {
  margin-bottom: 12px;
}

.icon-picker-body {
  max-height: 300px;
  overflow-y: auto;
}

.icon-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 12px;
}

.icon-item {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  background: #fff;
}

.icon-item:hover {
  border-color: #409eff;
  background: #f5f7fa;
  transform: scale(1.05);
}

.icon-item.active {
  border-color: #409eff;
  background: #ecf5ff;
  color: #409eff;
}

.icon-categories {
  margin-bottom: 12px;
}

.category-tabs {
  display: flex;
  gap: 8px;
  padding-bottom: 4px;
}

.category-tab {
  padding: 4px 12px;
  border-radius: 16px;
  background: #f5f7fa;
  color: #606266;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  white-space: nowrap;
}

.category-tab:hover {
  background: #e6e8eb;
  color: #303133;
}

.category-tab.active {
  background: #409eff;
  color: #fff;
}

.no-icons {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.no-icons p {
  margin-top: 12px;
  font-size: 14px;
}

.icon-count {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
}

.icon-picker-footer {
  margin-top: 12px;
  text-align: right;
  border-top: 1px solid #e4e7ed;
  padding-top: 8px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>